package com.ruoyi.client.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.client.pojo.form.UpdatePwdForm;
import com.ruoyi.client.pojo.form.UserLoginForm;
import com.ruoyi.client.pojo.form.UserRegisterForm;
import com.ruoyi.client.pojo.vo.UserLoginVo;
import com.ruoyi.client.pojo.vo.UserRegisterVo;
import com.ruoyi.client.pojo.vo.UserUpdatePwdVo;
import com.ruoyi.client.pojo.vo.UserVo;
import com.ruoyi.client.service.IClientUserService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.novel.domain.Users;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;

@Anonymous//允许匿名访问
@RestController
@RequestMapping("/user")
public class ClientUserController {
    private static final Logger logger = LoggerFactory.getLogger(ClientUserController.class);
    @Resource
    private IClientUserService userService;
    @Resource
    private ServerConfig serverConfig;

    @PostMapping ("/login")
    public AjaxResult login(@RequestBody UserLoginForm form){
//        调用服务层，登录验证
        UserVo userVo =userService.login(form);
        Long userId=userVo.getUserId();
//        登录 Sa-taken认证
        StpUtil.login(userId);
//        获取Token
        String token=StpUtil.getTokenValue();
//        封装返回数据
        UserLoginVo userLoginVo=new UserLoginVo();
        userLoginVo.setUser(userVo);
        userLoginVo.setToken(token);
        System.out.println();
//        返回接口数据
        return AjaxResult.success(userLoginVo);
    }
    // 用户注册
    @PostMapping("/register")
    public AjaxResult register(@RequestBody @Valid UserRegisterForm form){
        logger.info("接收到注册请求，表单数据: " + form);
        logger.info("表单中的头像URL: " + form.getAvatarUrl());
        
        // 调用服务层
        UserVo userVo = userService.register(form);
        
        logger.info("服务层返回的用户对象: " + userVo);
        if (userVo != null) {
            logger.info("返回用户对象中的头像URL: " + userVo.getAvatarUrl());
        }
        
        // 封装数据返回
        UserRegisterVo userRegisterVo = new UserRegisterVo();
        userRegisterVo.setUser(userVo);
        return AjaxResult.success(userRegisterVo);
    }
//    修改密码
    @PostMapping ("/updatePwd")
    public AjaxResult updatePwd(@RequestBody UpdatePwdForm form) {
        logger.info("接收到密码修改请求，表单数据: " + form);
        
        try {
            // 调用服务层更新密码
            int result = userService.updatePwd(form);
            logger.info("服务层密码修改返回结果: " + result);
            
            if (result > 0) {
                UserUpdatePwdVo updatePwdVo = new UserUpdatePwdVo();
                updatePwdVo.setPasswordNew(form.getPasswordNew());
                logger.info("密码修改成功，返回成功响应");
                return AjaxResult.success(updatePwdVo);
            } else {
                logger.error("密码修改失败，服务层返回结果: " + result);
                return AjaxResult.error("密码修改失败");
            }
        } catch (ServiceException e) {
            logger.error("密码修改业务异常: " + e.getMessage(), e);
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("密码修改系统异常: ", e);
            return AjaxResult.error("密码修改异常，请联系管理员");
        }
    }
    
    // 更新用户信息
    @PostMapping("/update")
    public AjaxResult updateUserInfo(@RequestBody Users user) {
        // 登录验证
        StpUtil.checkLogin();
        logger.info("用户Id:" + StpUtil.getLoginIdAsInt() + "/Token:" + StpUtil.getTokenValue());
        // 调用服务层
        int result = userService.updateUserInfo(user);
        // 数据返回
        if (result > 0) {
            return AjaxResult.success("用户信息更新成功");
        } else {
            return AjaxResult.error("用户信息更新失败");
        }
    }
//    用户详情页
    @GetMapping("/detail")
    public AjaxResult detail(@RequestParam Long id){
        // 登录验证
        StpUtil.checkLogin();
        logger.info("用户Id:" + StpUtil.getLoginIdAsInt() +  "/Token:" + StpUtil.getTokenValue());
        // 调用服务层
        UserVo userVo = userService.selectById(id);
        // 数据返回
        return AjaxResult.success(userVo);
    }


    @GetMapping("/logout")
    public AjaxResult logout(){
        StpUtil.logout();
        return AjaxResult.success();
    }

    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws Exception
    {
        try
        {
            // 打印调试信息
            logger.info("开始处理文件上传: " + file.getOriginalFilename());
            
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            logger.info("上传文件路径: " + filePath);
            
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            logger.info("上传后的文件名: " + fileName);
            
            String url = serverConfig.getUrl() + fileName;
            logger.info("完整URL: " + url);
            
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            logger.error("文件上传失败: ", e);
            return AjaxResult.error(e.getMessage());
        }
    }
}